package com.yunfinal.websocket;

import com.jfinal.plugin.IPlugin;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 模拟Java项目与项目之间相互连接
 */
public class ChatClient implements IPlugin {
    private final Timer timer = new Timer();
    private String serverUri;

    public static void main(String[] args) {
//        String serverUri = "ws://localhost:8887";
        String serverUri = "ws://localhost:8080/websocket.ws/123";
        ChatClient client = new ChatClient(serverUri);
        client.start();
    }

    public ChatClient(String serverUri) {
        this.serverUri = serverUri;
    }

    @Override
    public boolean start() {
        long period = 5 * 1000;
        timer.schedule(new WebSocketClientTask(), 1, period);
        return true;
    }

    @Override
    public boolean stop() {
        timer.cancel();
        return true;
    }


    private class WebSocketClientTask extends TimerTask {
        private WebSocketClient cc;

        @Override
        public void run() {
            try {
                if (Objects.isNull(cc)){
                    cc = new MyWebSocketClient();
                    cc.connectBlocking();
                }
                if (cc.isOpen()){
                    System.out.println("心跳检测正常");
                    return;
                }
                System.out.println("尝试重新连接。。。");
                cc.reconnectBlocking();

                if(cc.isOpen()){
                    System.out.println("重新连接成功");
                }
            } catch (Exception e) {
                System.out.println("连接异常");
            }
        }
    }

    private class MyWebSocketClient extends WebSocketClient{

        public MyWebSocketClient() {
            super(URI.create(serverUri));
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            System.out.println("onOpen:handshakedata="+handshakedata);
        }

        @Override
        public void onMessage(String message) {
            System.out.println("onMessage:message="+message);
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            System.out.println("onClose:code" + code + ", reason="+reason+", remote="+ remote);
        }

        @Override
        public void onError(Exception ex) {
            System.out.println("onError:" + ex);
        }
    }

}